<!--
 * @Descripttion: 字典管理
 * @version: 
 * @Author: wl
 * @Date: 2020-06-10 17:38:39
 * @LastEditors: wl
 * @LastEditTime: 2020-06-15 16:17:37
--> 

<template>
  <div>
    <page :asideShow="asideShow">
      <div slot="toolbar">
        <el-form :inline="true" :model="filters" label-width="90px" label-position="right">
          <el-form-item label="名称：">
            <el-input class="normal" placeholder="请输入查询内容" clearable v-model="filters.name"></el-input>
          </el-form-item>
          <el-form-item label="选择类型：">
            <el-select filterable clearable placeholder="选择类型" v-model="filters.DTID">
              <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item.DTID"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button @click="handleQuery('a')">查询</el-button>
        <el-button type="primary" @click="handleAdd" v-show="hasPerm('sys:dictionary:add')">新增</el-button>
      </div>
      <!--工具栏-->
      <div slot="content">
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          :data="pageResult"
          stripe
          v-loading="loading"
          style="width: 100%"
          element-loading-text="加载中..."
          @selection-change="handleSelectionChange"
        >
          <!-- <el-table-column type="selection"></el-table-column> -->
          <el-table-column prop="name" header-align="center" align="center" label="字典名"></el-table-column>
          <el-table-column prop="describe" header-align="center" align="center" label="描述"></el-table-column>
          <el-table-column prop="type" header-align="center" align="center" label="字典类型"></el-table-column>
          <el-table-column prop="type" header-align="center" align="center" label="父字典名" lazy>
            <template slot-scope="scope">
              <div>{{ scope.row.PDIDName ? scope.row.PDIDName : '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="type" header-align="center" align="center" label="创建人">
            <template slot-scope="scope">
              <div>{{ scope.row.goupName ? scope.row.goupName : '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
            <template slot-scope="scope">
              <el-button type="primary" :disabled="isDisabled(scope.row)" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button type="warn"  @click="handleHide(scope.row)">
                {{ scope.row.hide === true ? '显示' : '隐藏' }}
              </el-button>
              <el-button type="danger" :disabled="isDisabled(scope.row)" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.limit"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>
    </page>
    <!--新增编辑界面-->
    <el-dialog :title="operation ? '新增' : '编辑'" width="40%" :visible.sync="dialogVisible">
      <el-form :model="dataForm" label-width="80px" ref="dataForm">
        <el-form-item label="字典类型" prop="dType">
          <el-select filterable clearable placeholder="选择类型" v-model="dataForm.DTID" @change="pickDID">
            <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item.DTID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父类型" prop="PDID">
          <el-select filterable clearable placeholder="选择类型" v-model="dataForm.PDID">
            <el-option v-for="item in option_DID" :key="item.DID" :label="item.name" :value="item.DID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字典名" prop="name">
          <el-input v-model="dataForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述 " prop="describe">
          <el-input v-model="dataForm.describe" auto-complete="off"></el-input>
        </el-form-item>

        <!-- groupName -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click.native="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import KtTable from '@/views/Core/KtTable';
import KtButton from '@/views/Core/KtButton';
import { format } from '@/utils/datetime';
export default {
  components: {
    KtTable,
    KtButton
  },
  data() {
    return {
      flag: false,

      size: 'small',
      loading: false,
      filters: {
        name: '',
        DTID: '',
        dValue: '',
        endTime: ''
      },

      // 新增编辑界面数据
      dataForm: {
        DTID: '',
        name: '',
        describe: '',
        DID: '',
        PDID: ''
      },
      asideShow: false,

      pageRequest: { page: 1, limit: 10 },
      totalSize: 0,
      pageResult: [],
      showOperation: false,
      selections: [],
      operation: false,
      dialogVisible: false,
      options: [],
      option_DID: [],
      list: [],
      GID: ''
    };
  },
  methods: {
    // 判断是否禁用
    isDisabled(e) {
      if (this.GID === '1000') return false;
      if (!e.GID) return true;
      let idx = e.GID.indexOf(this.GID);
      if (idx === 0 && e.defined === true) return false;
      return true;
    },
    // 获取父类型名称
    getPDIDName(PDID) {
      let rs = this.list.find(it => it.DID === PDID);
      if (rs) return rs.name;
      return '-';
    },
    // 父类型选择DID类型
    async pickDID(e) {
      this.dataForm.PDID = '';
      this.option_DID = [];
      let param = {
        limit: 100,
        where: {
          DTID: e
        }
      };
      let rs = await this.$api.dict.findPage(param);
      this.option_DID = rs && rs.data && rs.code === 0 ? rs.data : [];
    },

    // 获取分页数据
    handleQuery: function(val) {
      let params = {
        where: {
          name: this.filters.name,
          DTID: this.filters.DTID
        },
        page: val ? '' : this.pageRequest.page,
        limit: val ? '' : this.pageRequest.limit
      };

      let paramJson = JSON.stringify(params);
      this.loading = true;
      this.$api.dict.findPage(paramJson).then(res => {
        if (res.code == 0) {
          this.loading = false;
          let arr = res.data;
          this.totalSize = res.count;
          arr.map(item => {
            item.type = item.dType[0].name;
          });
          arr.forEach(item => {
            if (item.PDID) {
              item.PDIDName = this.getPDIDName(item.PDID);
            } else {
            }
          });
          this.pageResult = arr;
        } else {
          this.$message({ message: '操作失败, ' + res.msg, type: 'error' });
        }
      });
    },
    // 获取字典类型
    dictType() {
      let params = {
        page: this.pageRequest.page,
        limit: 100
      };
      let paramJson = JSON.stringify(params);
      this.$api.dict.findPageType(paramJson).then(res => {
        if (res.code == 0) {
          this.options = res.data;
        } else {
          this.$message({ message: '操作失败, ' + res.msg, type: 'error' });
        }
      });
    },

    //去重复后的集合
    listPush(res) {
      var tem = [];
      //数组元素去重
      return tem;
    },
    // 显示新增界面
    handleAdd: function() {
      this.dialogVisible = true;
      this.operation = true;
      this.dataForm = {
        DTID: '',
        name: '',
        describe: '',
        DID: '',
        PDID: ''
      };
    },
    async hasAuthToHide() {},
    // 是否隐藏改字典
    async handleHide(e) {
      try {
        let msg = '是否在其它功能当中隐藏该字典！';
        let operation = 1;
        if (e.hide === true) {
          msg = '是否在其它功能当中展示该字典！';
          operation = 2;
        }
        let rs = await this.$confirm(msg, '提示', {
          type: 'warning'
        });
        if (rs !== 'confirm') return;
        let res = await this.$api.dict.sys_dictionaries_filter({
          DTID: e.DTID,
          DID: e.DID,
          GID: e.GID ? e.GID : this.GID,
          operation: operation
        });
        if (res && res.code === 0)
          this.$message({
            showClose: true,
            message: '操作成功！',
            type: 'success'
          });
        this.handleQuery();
      } catch (err) {
        if (err === 'cancel') return;
        this.$message({
          showClose: true,
          message: '操作失败！',
          type: 'error'
        });
      }
    },
    // 显示编辑界面
    handleEdit: function(params) {
      this.dialogVisible = true;
      this.operation = false;
      this.pickDID(params.DTID);
      this.dataForm = Object.assign({}, params);
    },
    //删除
    handleDelete(row) {
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        let params = {
          DID: row.DID
        };

        var paramJson = JSON.stringify(params);
        this.$api.dict.batchDelete(paramJson).then(res => {
          if (res.code == 0) {
            this.handleQuery();
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          } else {
            this.$message({
              message: '操作失败, ' + res.msg,
              type: 'error'
            });
          }
        });
      });
    },
    // 批量删除
    batchDelete() {
      this.$confirm('确认删除选中用户吗？', '提示', 'warning').then(() => {
        let selLength = this.selections.length;
        let totalLength = this.pageResult.length;
        let isReduce = selLength == totalLength ? true : false;
        let params = this.selections
          .map(item => {
            return item.DID;
          })
          .join(',');
        this.$api.dict
          .batchDelete({
            DID: params
          })
          .then(res => {
            if (res.code == 0) {
              this.$message.success('删除成功');
              if (isReduce) {
                this.pageRequest.page--;
              }
              this.handleQuery();
            } else {
              this.$message.error(res.msg);
            }
          });
      });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            let params = {
              ...this.dataForm
            };

            let paramJson = JSON.stringify(params);
            this.$api.dict.save(paramJson).then(res => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.$refs['dataForm'].resetFields();
              } else {
                this.$message({
                  message: '操作失败, ' + res.msg,
                  type: 'error'
                });
              }
              this.handleQuery(null);
            });
          });
        }
      });
    },
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    },
    handleSelectionChange(val) {
      this.selections = val;
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    }
  },
  async mounted() {
    let rs = await this.$api.dict.findPage({
      limit: 1000
    });
    this.GID = JSON.parse(sessionStorage.getItem('userInfo')).GID;
    this.list = rs.code === 0 && rs.data ? rs.data : [];
    this.handleQuery();
    this.dictType();
  }
};
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
